package com.yaodian100.crm.activities.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.form.entity.Attribute;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.crm.activities.entity.Mgm;
import com.yaodian100.crm.activities.entity.MgmCoupon;
import com.yaodian100.crm.activities.entity.MgmValue;
import com.yaodian100.ec.coupon.entity.CouponItem;

public class MgmServiceImp implements MgmService {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private BaseManager baseMgr;
	@Resource
	private TemplateService templateService;
	@Autowired
	private MailService mailService;
	private String mailFrom;

	public String getMailFrom() {
		return mailFrom;
	}

	public void setMailFrom(String mailFrom) {
		this.mailFrom = mailFrom;
	}

	@Override
	public String addMgmInfo(String typeName, Map<String, String> values, String ToEmail, String couponId, String memberId) {
		Object[] type = baseMgr.queryByHql("from Attribute where form.name=?", new Object[] { typeName });
		Mgm mgm = new Mgm();
		mgm.setCouponId(couponId);
		mgm.setMemberId(memberId);
		baseMgr.save(mgm);
		return null;
	}

	@Override
	@Transactional(readOnly = false)
	public Mgm addMgmInfo(String memberId, String coupon, String userToEmail, String userName) {
		String questionTypeName = "mgm";
		Map<String, String> values = new HashMap<String, String>();
		values.put("memberId", memberId);
		values.put("couponId", coupon);
		values.put("userToEmail", userToEmail);
		// values.put("type", type);
		Mgm mgm = createMgmBase(questionTypeName, values);
		System.out.println("=======查询memberid========");
		String basehref = ServerValue.getFrontHostname();
		System.out.println(basehref);
		mgmToMail(values.get("userToEmail"), values.get("couponId"), userName, basehref);
		return mgm;
	}

	private Mgm createMgmBase(String questionTypeName, Map<String, String> values) {
		Object[] type = baseMgr.queryByHql("from Attribute where form.name=?", new Object[] { questionTypeName });
		Mgm mgm = new Mgm();
		mgm.setMemberId(values.get("memberId"));
		mgm.setCouponId(values.get("couponId"));
		baseMgr.save(mgm);
		Map<String, MgmValue> valueMap = new HashMap<String, MgmValue>();
		for (Object obje : type) {
			Attribute attribute = (Attribute) obje;
			if (attribute.getDataType().equals("Button")) {
				continue;
			}
			MgmValue mgmValue = new MgmValue();
			mgmValue.setMgm(mgm);
			mgmValue.setName(attribute.getName());
			mgmValue.setAttribute(attribute);
			// Date createDT = new Date();
			// mgmValue.setCreateDate(createDT);
			for (String key : values.keySet()) {
				if (mgmValue.getName().equals(key)) {
					Object obj = values.get(key);
					String value = null;
					if (obj instanceof String[]) {
						value = ((String[]) obj)[0];
					} else {
						value = (String) obj;
					}
					mgmValue.setValue(value);
				}
			}
			baseMgr.save(mgmValue);
			// mgmtomail(values.get("userToEmail"), values.get("couponId"));

			valueMap.put(mgmValue.getName(), mgmValue);
		}
		mgm.setMgmValue(valueMap);
		return mgm;
	}

	@Override
	public String addMgmCoupon(List<Map<String, String>> values) {
		MgmCoupon mgmCoupon = null;
		if (values.size() > 0) {
			for (Map<String, String> map : values) {
				mgmCoupon = new MgmCoupon();

				mgmCoupon.setMemberId(map.get("memberId"));
				mgmCoupon.setCouponId(map.get("couponId"));
				mgmCoupon.setCouponName(map.get("couponName"));
				mgmCoupon.setIsuse(Integer.parseInt(map.get("isuse")));
				baseMgr.save(mgmCoupon);
			}

		}

		return null;
	}

	@Override
	public String addMgmCoupon(String memberId, String couponId, String couponName, int isuse) {

		MgmCoupon mgmCoupon = new MgmCoupon();
		mgmCoupon.setMemberId(memberId);
		mgmCoupon.setCouponId(couponId);
		mgmCoupon.setCouponName(couponName);
		mgmCoupon.setIsuse(isuse);
		baseMgr.save(mgmCoupon);
		return null;

	}

	@Override
	public List<CouponItem> getCouponId(String couponUuid) {

		List<CouponItem> list = new ArrayList<CouponItem>();

		Object[] type = baseMgr.queryByHql("from CouponItem where coupon=? ", new Object[] { couponUuid });
		if (type.length > 0) {

			for (Object object : type) {

				CouponItem couponItem = (CouponItem) object;

				list.add(couponItem);

			}
		}
		return list;

	}

	@Override
	public List<MgmCoupon> findMgmCoupon(String memberId) {

		Object[] type = baseMgr.queryByHql("from MgmCoupon where memberId=? and isuse=?", new Object[] { memberId, 0 });
		List<MgmCoupon> list = new ArrayList<MgmCoupon>();
		if (type.length > 0) {

			for (Object object : type) {

				MgmCoupon mgmCoupon = (MgmCoupon) object;

				list.add(mgmCoupon);

			}
		}

		return list;
	}

	// @SuppressWarnings("unused")
	// private boolean tomail(String toemail, String couponId) {
	// boolean verdict = false;
	// try {
	//
	// Mail mail = templateService.formatToMail("testMail", null);
	// mail.addTo("朋友", toemail);
	// mail.setFrom("yanling.wu@yaodian100.com");
	// mail.setSubject("一人得到，一起升天");
	// mail.setBody("<table><tr><td>你好的朋友送你一张礼券：" + couponId + "</td></tr></table>");
	// verdict = mailService.sendMail(mail);
	// logger.debug("send mail");
	// System.out.println("==============华丽的分割线=============================");
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return verdict;
	// }

	@Override
	public boolean mgmtomail(String toemail, String couponId) throws CoreException {

		Map<String, Object> contentMap = new HashMap<String, Object>();
		StringBuilder urllink = new StringBuilder("");
		contentMap.put("couponId", couponId);
		contentMap.put("contextpath", ServerValue.getFrontContextPath());
		contentMap.put("customerFax", ServerValue.getCustomerFax());
		contentMap.put("customerTel", ServerValue.getCustomerTel());
		contentMap.put("urllink", urllink.toString());
		Mail mail = templateService.formatToMail("member.mgm", contentMap);
		mail.setTo(toemail);
		mail.setFrom(mailFrom);
		mailService.save(mail);
		urllink.setLength(0);

		return false;
	}

	public boolean mgmToMail(String toemail, String couponId, String userName, String basehref) {

		System.out.println("==============华丽的分割线=============================");
		Map<String, Object> contentMap = new HashMap<String, Object>();
		StringBuilder urllink = new StringBuilder("");
		contentMap.put("loginId", userName);
		contentMap.put("basehref", basehref);
		contentMap.put("couponId", couponId);// 礼券号
		contentMap.put("contextpath", ServerValue.getFrontContextPath());// /ecmall
		contentMap.put("customerFax", ServerValue.getCustomerFax());
		contentMap.put("customerTel", ServerValue.getCustomerTel());
		contentMap.put("urllink", urllink.toString());
		System.out.println(urllink.toString());
		Mail mail = templateService.formatToMail("member.mgm", contentMap);
		mail.setTo(toemail);// 要发送 的mail
		mailService.save(mail);
		urllink.setLength(0);
		System.out.println("==============华丽的分割线  ====end=============================");
		MgmCoupon mgmCoupon = getMgmCoupon(couponId, "0");
		mgmCoupon.setIsuse(1);
		System.out.println("=====华丽的 更改mgm  coupon  数据===================");
		mgmCoupon.setUserName(userName);
		baseMgr.save(mgmCoupon);

		return false;

	}

	@Override
	public String updateMgmCoupon(String mgmCouponid, String memberId) {
		MgmCoupon mgmCoupon = getMgmCoupon(mgmCouponid, "1");
		mgmCoupon.setToMemeberId(memberId);
		baseMgr.update(mgmCoupon);
		return null;
	}

	@Override
	public MgmCoupon getMgmCouponInfo(String mgmCouponid) {
		return getMgmCoupon(mgmCouponid, "1");

	}

	@Override
	public CouponItem getCoupon(String mgmCouponid) {
		System.out.println("==========holle============");
		return getCouponItem(mgmCouponid);

	}

	private CouponItem getCouponItem(String couponId) {
		CouponItem couponItem = null;
		Object[] type = baseMgr.queryByHql("from CouponItem where code=?", new Object[] { couponId });

		if (type.length > 0) {

			for (Object object : type) {

				couponItem = (CouponItem) object;

			}
		}

		return couponItem;
	}

	private MgmCoupon getMgmCoupon(String mgmCouponid, String i) {
		MgmCoupon mgmCoupon = null;

		Object[] type = baseMgr.queryByHql("from MgmCoupon where couponId=? and isuse=?", new Object[] { mgmCouponid, i });

		if (type.length > 0) {

			for (Object object : type) {

				mgmCoupon = (MgmCoupon) object;

			}
		}

		return mgmCoupon;
	}

	@Override
	public MgmCoupon checkMgmMember(String tomemnerId) {
		Object[] type = baseMgr.queryByHql("from MgmCoupon where toMemeberId=?", new Object[] { tomemnerId });
		MgmCoupon mgmCoupon = null;
		if (type.length > 0) {

			for (Object object : type) {

				mgmCoupon = (MgmCoupon) object;

			}
		}

		return mgmCoupon;
	}

	@Override
	public String updateIsuseCoupon(String mgmCouponid) {
		MgmCoupon mgmCoupon = getMgmCoupon(mgmCouponid, "1");
		mgmCoupon.setIsuse(2);
		System.out.println("=====华丽的 更改mgm  coupon 已充值  数据  ===================");
		baseMgr.update(mgmCoupon);

		return null;
	}
}